package eg9_12;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;

public class WindowsList extends JFrame {
    private JList<String> jList1;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    private JTextArea jTextArea1;
    public WindowsList() {
        jScrollPane1 = new JScrollPane();
        jList1 = new JList<>();
        jScrollPane2 = new JScrollPane();
        jTextArea1 = new JTextArea();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jList1.setModel(new javax.swing.AbstractListModel<String>() {
            final String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            @Override
            public int getSize() {
                return strings.length;
            }
            @Override
            public String getElementAt(int i) {
                return strings[i];
            }
        });
        // 设置 JList 的选择模式为多选
        jList1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        jList1.addListSelectionListener(this::jList1ValueChange);
        jScrollPane1.setViewportView(jList1);
        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);
        this.setLayout(new FlowLayout());
        this.add(jTextArea1);
        this.add(jList1);
        this.setBounds(200,100,600,400);
        this.setTitle("JList列表演示");
        this.setVisible(true);
    }
    private void jList1ValueChange(ListSelectionEvent e) {
        this.jTextArea1.setText("");
        if(!e.getValueIsAdjusting()) {
            int[] selectIndex=this.jList1.getSelectedIndices();
            for(int i:selectIndex) {
                System.out.println(i+",");
                this.jTextArea1.append(this.jList1.getModel().getElementAt(i) + " ");
            }
        }
    }
}
